(ns acst.models.news
  (:use acst.config.error-config
        acst.config.success-config)
  (:require [clojure.java.jdbc :as sql]
            [acst.models.comments :refer :all]
            [acst.utils.sql-util :as sqlutil]
            [acst.utils.escape :refer [html-sanitizer]]
            [acst.models.db :as db]))

(defn find-all-news [limit page]
  (db/query
    (:new-not-found news-error)
    ["SELECT news_id, create_date, publisher_id, username, title, content
     FROM news,users WHERE user_id = publisher_id ORDER BY create_date LIMIT ? OFFSET ?" limit (* (- page 1) limit)]))

(defn find-news-by-newid [news_id]
  (db/query
    (:new-not-found news-error)
    ["SELECT news_id, create_date, publisher_id, username, title, content
    FROM news,users WHERE user_id = publisher_id AND news_id = ?" news_id]))

(defn insert-news! [publisher_id title content]
  (if (= '(1) (db/insert! :news
              {:publisher_id publisher_id
               :title (html-sanitizer title)
               :content (html-sanitizer content)}))
  (:add-news-failed news-error)
  (:add-news-success news-result)))

(defn delete-news! [news_id]
  (if (= '(1) (db/delete! :news ["news_id = ?" news_id]))
    (:delete-news-success news-result)
    (:delete-news-failed news-error)))

(defn insert-news-comment! [news_id publisher_id content reply_id]
  (insert-comment! :news_comments news_id publisher_id content reply_id)) ;;comments已做防xss处理

(defn find-news-comments [news_id limit page]
  (get-all-comment :news_comments news_id limit page))

(defn find-news-comments-reply-tree [news_id comment_id]
  (get-comment-reply-tree :news_comments news_id comment_id))

(defn delete-news-comment! [news_id comment_id user_id]
  (delete-comment! :news_comments news_id comment_id user_id))